package com.itcast.netty.client;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 业务处理类
 *
 * @author zheng.zhang
 */
@Slf4j
public class TimeClientHandler extends ChannelInboundHandlerAdapter {
    public static final int RETRY_NUM = 10;
    private final byte[] req;

    public TimeClientHandler() {
        req = "$tmb00035ET3318/08/22 11:5704026.75,027.31,20.00,20.00$".getBytes();
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        for (int i = 0; i < RETRY_NUM; i++) {
            ByteBuf message = Unpooled.buffer(req.length);
            message.writeBytes(req);
            ctx.writeAndFlush(message);
        }
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        try {
            ByteBuf buf = (ByteBuf) msg;
            log.info(buf.toString(CharsetUtil.UTF_8));
        } catch (Exception e) {
            log.error("读取出错");
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // 出现异常就关闭
        cause.printStackTrace();
        ctx.close();
    }
}
